package org.game.module.endlesscloisterbo;

import java.util.ArrayList;
import java.util.List;

import org.cfg.cache.EndlessCloisterLevelCfgCache;
import org.error.GameErrorCode;
import org.game.constant.EndlessCloisterConstant;
import org.game.constant.SessionConstent;
import org.game.db.bean.Player;
import org.game.db.bean.PlayerData;
import org.game.db.proxy.bean.PlayerDataProxy;
import org.game.db.vo.PlayerDataVO.EndlessVO;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.GoodsDsp;
import org.game.manager.EndlessCloisterManager;
import org.game.manager.ItemManager;
import org.game.msgBuilder.EndlessCloisterMsgBuilder;
import org.game.protobuf.c2s.C2SEndlessCloisterMsg.ReqEndlessCloisterInfo;
import org.game.protobuf.c2s.C2SEndlessCloisterMsg.ReqPassStageEndless;
import org.game.protobuf.c2s.C2SEndlessCloisterMsg.ReqStartFightEndless;
import org.game.protobuf.s2c.S2CEndlessCloisterMsg.RspEndlessCloisterInfo;
import org.game.protobuf.s2c.S2CShareMsg.RewardsMsg;
import org.game.util.ProtoUnit;

import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.factory.session.ISession;
import com.sojoys.artifact.manager.MessageManager;
import com.sojoys.artifact.tools.ToolError;
import com.xiaoleilu.hutool.util.MapUtil;

/**
 * 无尽回廊
 * 
 * @author liu.jiang
 * @date 2018年3月13日
 */
public class EndlessCloisterBOImpl implements EndlessCloisterBO {

    @Override
    public byte[] getInfo(ISession session, ReqEndlessCloisterInfo msg)
            throws AbstractLogicModelException {
        Player player = session.getAttr(SessionConstent.PLAYER);
        return ProtoUnit.toByte(EndlessCloisterMsgBuilder.createEndlessCloisterInfo(player));
    }

    @Override
    public byte[] startFight(ISession session, ReqStartFightEndless msg)
            throws AbstractLogicModelException {
        Player player = session.getAttr(SessionConstent.PLAYER);
        // TODO 后续添加消耗检测
        PlayerData playerData = player.getPlayerDatasFkPlayerId();
        PlayerDataProxy pdProxy = playerData.getPlayerDataProxy();
        EndlessVO endlessVO = pdProxy.getEndlessVO();
        int startStageId = 0;
        if (EndlessCloisterManager.me().getStep() == EndlessCloisterConstant.STEP_OPEN) {// 活动开启阶段
            if (endlessVO.getNowStage() <= 0) {
                startStageId = EndlessCloisterManager.me().getInitStageId();
                endlessVO.setNowStage(startStageId);
            } else {
                startStageId = endlessVO.getNowStage();
            }
            pdProxy.save();
        }
        RspEndlessCloisterInfo info = EndlessCloisterMsgBuilder.createEndlessCloisterInfo(player);
        player.getPlayerProxy().sendMsg(
                MessageManager.me().create(EndlessCloisterBO.getInfo, ProtoUnit.toByte(info)));
        return ProtoUnit.toByte(EndlessCloisterMsgBuilder.createRspStartFightEndless(endlessVO,
                startStageId));
    }

    @Override
    public byte[] passStage(ISession session, ReqPassStageEndless msg)
            throws AbstractLogicModelException {
        Player player = session.getAttr(SessionConstent.PLAYER);
        PlayerData playerData = player.getPlayerDatasFkPlayerId();
        PlayerDataProxy pdProxy = playerData.getPlayerDataProxy();
        EndlessVO endlessVO = pdProxy.getEndlessVO();
        int stageId = endlessVO.getNowStage();// 关卡id
        ToolError.isAndTrue(GameErrorCode.ENDLESS_STAGE_NOT_MATCH, msg.getLevelCid() != stageId);
        int costTime = msg.getCostTime();// 耗时（秒）
        endlessVO.setTodayCostTime(endlessVO.getTodayCostTime() + costTime);
        endlessVO.setLastPassTime(System.currentTimeMillis());

        // 计算下一关卡
        List<RewardsMsg> rewards = new ArrayList<RewardsMsg>();
        int nextStageId = 0;
        if (EndlessCloisterManager.me().getStep() == EndlessCloisterConstant.STEP_OPEN
                || EndlessCloisterManager.me().getStep() == EndlessCloisterConstant.STEP_BALANCE) {// 活动开启或结算阶段
            nextStageId = EndlessCloisterManager.me().getNextStageId(stageId, costTime);
            endlessVO.setNowStage(nextStageId);
            if (nextStageId > 0) {
                int bestStage = nextStageId - 1;// 今日最高通关关卡id
                endlessVO.setTodayBest(bestStage);// 因为后续要根据关卡id发奖，所以这里保存的是关卡id
                int best = EndlessCloisterLevelCfgCache.me().getById(bestStage).getOrder();
                if (best > endlessVO.getHistoryBest()) {
                    endlessVO.setHistoryBest(best);
                }
                // 通关奖励
                for (int i = stageId; i <= bestStage; i++) {
                    LogDsp logDsp =
                            LogDsp.newBuilder(GoodsDsp.ENDLESS_CLOISTER_PASS).addAttr("stageId",
                                    stageId);
                    rewards.addAll(ItemManager.unpackNotify(
                            player,
                            MapUtil.of(EndlessCloisterLevelCfgCache.me().getById(stageId)
                                    .getReward(), 1), logDsp));
                }
            }
            if (EndlessCloisterManager.me().getStep() == EndlessCloisterConstant.STEP_BALANCE) {
                nextStageId = 0;
            }
        }
        pdProxy.save();
        RspEndlessCloisterInfo info = EndlessCloisterMsgBuilder.createEndlessCloisterInfo(player);
        player.getPlayerProxy().sendMsg(
                MessageManager.me().create(EndlessCloisterBO.getInfo, ProtoUnit.toByte(info)));
        return ProtoUnit.toByte(EndlessCloisterMsgBuilder.createRspPassStageEndless(endlessVO,
                rewards, nextStageId));
    }

}
